package com.zhang.servlet;

import com.github.pagehelper.PageInfo;
import com.zhang.pojo.ManBean;
import com.zhang.service.IManService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
public class FindAllServlet extends HttpServlet {
    @Autowired
    private IManService manService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset = utf-8");

        //得到页码
        String page = req.getParameter("pageNo");
        int pageNo = 1;
        if (page != null){
            pageNo = Integer.parseInt(page);
        }

        //调用业务方法得到分页集合
        PageInfo<ManBean> all = manService.findAll(pageNo);
        //得到当前页显示的记录
        List<ManBean> list = all.getList();
        //获得总页数
        int pages = all.getPages();

        StringBuffer buffer = new StringBuffer();
        buffer.append("<table border=\"1\" width=\"60%\" cellspacing=\"0\">");
        buffer.append("<thead>\n" +
                "            <tr>\n" +
                "                <th>姓名</th>\n" +
                "                <th>生日</th>\n" +
                "                <th>操作</th>\n" +
                "            </tr>\n" +
                "        </thead>");
        buffer.append("<tbody>");
        for (ManBean manBean:list) {
            buffer.append("<tr>\n" +
                    "                <td>"+manBean.getName()+"</td>\n" +
                    "                <td>"+manBean.getBirthday()+"</td>\n" +
                    "                <td>" +
                    "                   <a href='/del?delId="+manBean.getId()+"'>删除</a>" +
                    "                   <a href='/toUpdate?upId="+manBean.getId()+"'>修改</a>" +
                    "                </td>\n" +

                    "            </tr>");
        }
        buffer.append("</tbody>\n" +
                "    </table>");

        for (int i = 1; i <= pages ; i++) {
            buffer.append("<a style=\"margin-left: 10px\" href='/findAll?pageNo="+i+"' >"+i+"</a>" );
        }

//        buffer.append("<a href='addMan.html'>添加公民</a>");


        resp.getWriter().println(buffer.toString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
